<template>
  <el-dialog
    v-model="visible"
    title="AI评估结果"
    width="800px"
    :close-on-click-modal="false"
    top="5vh"
  >
    <div class="evaluation-result-content" v-loading="loading">
      <!-- 错误状态 -->
      <div v-if="error" class="error-state">
        <el-alert
          :title="error"
          type="error"
          :closable="false"
          show-icon
        />
        <div class="error-actions">
          <el-button @click="handleRefresh">重新获取</el-button>
          <el-button type="primary" @click="handleClose">关闭</el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!evaluationData" class="empty-state">
        <el-empty description="暂无评估结果">
          <el-button type="primary" @click="handleClose">
            关闭
          </el-button>
        </el-empty>
      </div>

      <!-- 评估结果内容 -->
      <div v-else class="result-content">
        <!-- 评估状态 -->
        <div class="status-section">
          <el-alert
            :title="getStatusTitle()"
            :type="getStatusType()"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="status-info">
                <p>评估时间：{{ formatTime(evaluationData.evaluation_at) }}</p>
                <p v-if="evaluationData.job_position">
                  评估岗位：{{ getJobTitle(evaluationData.job_position) }}
                </p>
              </div>
            </template>
          </el-alert>
        </div>

        <!-- 评估内容 -->
        <div class="content-section">
          <div class="content-header">
            <h3>评估报告</h3>
            <div class="header-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleDownload"
                :loading="downloadLoading"
              >
                <el-icon><Download /></el-icon>
                下载报告
              </el-button>
              <el-button
                size="small"
                @click="handleCopyContent"
              >
                <el-icon><CopyDocument /></el-icon>
                复制内容
              </el-button>
            </div>
          </div>

          <div class="markdown-content">
            <div
              class="markdown-body"
              v-html="renderedContent"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button
          v-if="evaluationData && evaluationData.has_file"
          type="primary"
          @click="handleDownload"
          :loading="downloadLoading"
        >
          <el-icon><Download /></el-icon>
          下载报告
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, CopyDocument } from '@element-plus/icons-vue'
import { marked } from 'marked'
import type { Resume } from '@/api/resume'
import { formatTime } from '@/utils/format'
import { resumeApi } from '@/api/resume'

interface Props {
  modelValue: boolean
  resume: Resume | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'download', resume: Resume): void
}

interface EvaluationData {
  status: string
  content: string
  evaluation_at: string
  job_position: string
  has_file: boolean
  download_url: string | null
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const downloadLoading = ref(false)
const evaluationData = ref<EvaluationData | null>(null)
const error = ref('')

// 监听 modelValue 变化
watch(() => props.modelValue, (newValue) => {
  visible.value = newValue
  if (newValue && props.resume) {
    fetchEvaluationData()
  }
})

// 监听 visible 变化
watch(visible, (newValue) => {
  emit('update:modelValue', newValue)
  if (!newValue) {
    // 关闭时清理数据
    evaluationData.value = null
    error.value = ''
  }
})

// 获取评估数据
const fetchEvaluationData = async () => {
  if (!props.resume) return

  loading.value = true
  error.value = ''

  try {
    const response = await resumeApi.getAIEvaluation(props.resume.id)
    evaluationData.value = response.data
  } catch (err: any) {
    console.error('获取AI评估结果失败:', err)
    error.value = err.response?.data?.error || '获取评估结果失败'
  } finally {
    loading.value = false
  }
}

// 刷新数据
const handleRefresh = () => {
  fetchEvaluationData()
}

// 渲染的Markdown内容
const renderedContent = computed(() => {
  if (!evaluationData.value?.content) return ''

  try {
    return marked(evaluationData.value.content)
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return `<pre>${evaluationData.value.content}</pre>`
  }
})

// 获取状态标题
const getStatusTitle = () => {
  if (!evaluationData.value) return ''

  switch (evaluationData.value.status) {
    case 'completed':
      return 'AI评估已完成'
    case 'in_progress':
      return 'AI评估进行中'
    case 'failed':
      return 'AI评估失败'
    default:
      return '未开始评估'
  }
}

// 获取状态类型
const getStatusType = () => {
  if (!evaluationData.value) return 'info'

  switch (evaluationData.value.status) {
    case 'completed':
      return 'success'
    case 'in_progress':
      return 'warning'
    case 'failed':
      return 'error'
    default:
      return 'info'
  }
}

// 从岗位信息中提取岗位标题
const getJobTitle = (jobPosition: string) => {
  const lines = jobPosition.split('\n')
  const titleLine = lines.find(line => line.includes('岗位名称：'))
  if (titleLine) {
    return titleLine.replace('岗位名称：', '').trim()
  }
  return '未知岗位'
}

// 处理下载
const handleDownload = () => {
  if (!props.resume) return
  downloadLoading.value = true
  
  try {
    emit('download', props.resume)
  } finally {
    // 延迟重置loading状态，给用户反馈
    setTimeout(() => {
      downloadLoading.value = false
    }, 1000)
  }
}

// 处理复制内容
const handleCopyContent = async () => {
  if (!evaluationData.value?.content) return

  try {
    await navigator.clipboard.writeText(evaluationData.value.content)
    ElMessage.success('内容已复制到剪贴板')
  } catch (error) {
    // 降级方案：使用传统的复制方法
    const textArea = document.createElement('textarea')
    textArea.value = evaluationData.value.content
    document.body.appendChild(textArea)
    textArea.select()

    try {
      document.execCommand('copy')
      ElMessage.success('内容已复制到剪贴板')
    } catch (err) {
      ElMessage.error('复制失败，请手动复制')
    }

    document.body.removeChild(textArea)
  }
}

// 处理关闭
const handleClose = () => {
  visible.value = false
}
</script>

<style lang="scss" scoped>
.evaluation-result-content {
  .error-state {
    padding: 20px 0;

    .error-actions {
      margin-top: 16px;
      text-align: center;

      .el-button {
        margin: 0 8px;
      }
    }
  }

  .empty-state {
    padding: 40px 0;
    text-align: center;
  }

  .result-content {
    .status-section {
      margin-bottom: 20px;

      .status-info {
        p {
          margin: 4px 0;
          font-size: 14px;
          line-height: 1.4;
        }
      }
    }

    .content-section {
      .content-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid var(--border-color-light);

        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: var(--text-color-primary);
        }

        .header-actions {
          display: flex;
          gap: 8px;
        }
      }

      .markdown-content {
        max-height: 60vh;
        overflow-y: auto;
        border: 1px solid var(--border-color-light);
        border-radius: 6px;
        padding: 20px;
        background: var(--fill-color-extra-light);

        .markdown-body {
          line-height: 1.6;
          color: var(--text-color-primary);

          :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
            margin: 16px 0 8px 0;
            font-weight: 600;
            color: var(--text-color-primary);
          }

          :deep(h1) { font-size: 24px; }
          :deep(h2) { font-size: 20px; }
          :deep(h3) { font-size: 18px; }
          :deep(h4) { font-size: 16px; }
          :deep(h5) { font-size: 14px; }
          :deep(h6) { font-size: 13px; }

          :deep(p) {
            margin: 8px 0;
            line-height: 1.6;
          }

          :deep(ul), :deep(ol) {
            margin: 8px 0;
            padding-left: 20px;

            li {
              margin: 4px 0;
              line-height: 1.5;
            }
          }

          :deep(blockquote) {
            margin: 16px 0;
            padding: 12px 16px;
            background: var(--color-info-light-9);
            border-left: 4px solid var(--color-info);
            border-radius: 4px;
          }

          :deep(code) {
            padding: 2px 4px;
            background: var(--fill-color-light);
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
          }

          :deep(pre) {
            margin: 16px 0;
            padding: 16px;
            background: var(--fill-color-light);
            border-radius: 6px;
            overflow-x: auto;

            code {
              padding: 0;
              background: none;
            }
          }

          :deep(table) {
            width: 100%;
            border-collapse: collapse;
            margin: 16px 0;

            th, td {
              padding: 8px 12px;
              border: 1px solid var(--border-color-light);
              text-align: left;
            }

            th {
              background: var(--fill-color-light);
              font-weight: 600;
            }
          }

          :deep(hr) {
            margin: 20px 0;
            border: none;
            border-top: 1px solid var(--border-color-light);
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .evaluation-result-content {
    .result-content {
      .content-section {
        .content-header {
          flex-direction: column;
          align-items: flex-start;
          gap: 12px;

          .header-actions {
            width: 100%;
            justify-content: flex-end;
          }
        }

        .markdown-content {
          max-height: 50vh;
          padding: 16px;
        }
      }
    }
  }
}
</style>
